<template>
  <div class="app-container">
    <!-- 设备列表页面 -->
    <div >
      <el-card>
        <!-- 搜索区域 -->
        <el-row :gutter="20">
          <el-col :span="5">
            <el-input v-model="searchForm.keyword" placeholder="设备编号/名称" clearable />
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.type" placeholder="设备类型" clearable>
              <el-option v-for="item in equipmentTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.status" placeholder="设备状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="searchForm.area" placeholder="所属区域" clearable>
              <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="5" class="mt-2">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width: 100%;" />
          </el-col>
          <el-col :span="5" class="mt-2">
            <el-input v-model="searchForm.model" placeholder="设备型号" clearable />
          </el-col>
          <el-col :span="5" class="mt-2">
            <el-input v-model="searchForm.location" placeholder="安装位置" clearable />
          </el-col>
          <el-col :span="5" class="mt-2">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
        <div class="mt-2">
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="batchDelete">批量删除</el-button>
          <el-button type="primary" @click="showAddDialog">新增设备</el-button>
        </div>
        <!-- 设备表格 -->
        <el-table class="mt-2" :data="equipmentList" border style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="设备编号" />
          <el-table-column prop="name" label="设备名称" />
          <el-table-column prop="type" label="设备类型" />
          <el-table-column prop="model" label="型号" />
          <el-table-column prop="status" label="运行状态">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="years" label="使用年限" />
          <el-table-column prop="area" label="所属区域" />
          <el-table-column prop="location" label="安装位置" />
          <el-table-column prop="maintenanceCycle" label="维护周期" />
          <el-table-column label="操作" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="showEquipmentDetail(row)">详情</el-button>
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量操作和分页 -->
        <div class="mt-2" style="text-align: right;">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 设备详情页面 -->
    <el-dialog v-model="dateilVisible" title="详情" width="50%">
      <div class="detail-header">
        <h2>设备详情 - {{ currentEquipment.name }}</h2>
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="基础信息" name="basic"></el-tab-pane>
          <el-tab-pane label="技术参数" name="tech"></el-tab-pane>
          <el-tab-pane label="运行状态" name="status"></el-tab-pane>
          <el-tab-pane label="维护记录" name="maintenance"></el-tab-pane>
          <el-tab-pane label="故障记录" name="fault"></el-tab-pane>
          <el-tab-pane label="设备档案" name="files"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 基础信息 -->
      <div v-if="activeTab === 'basic'" class="detail-content">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备编号">{{
            currentEquipment.id
          }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{
            currentEquipment.name
          }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{
            currentEquipment.type
          }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{
            currentEquipment.model
          }}</el-descriptions-item>
          <el-descriptions-item label="生产厂商">{{
            currentEquipment.manufacturer
          }}</el-descriptions-item>
          <el-descriptions-item label="出厂日期">{{
            currentEquipment.productionDate
          }}</el-descriptions-item>
          <el-descriptions-item label="安装日期">{{
            currentEquipment.installationDate
          }}</el-descriptions-item>
          <el-descriptions-item label="使用年限">{{
            currentEquipment.years
          }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">位置信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="所属区域">{{
            currentEquipment.area
          }}</el-descriptions-item>
          <el-descriptions-item label="安装位置">{{
            currentEquipment.location
          }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{
            currentEquipment.manager
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentEquipment.phone
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 技术参数 -->
      <div v-if="activeTab === 'tech'" class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="流量">10dm³/h</el-descriptions-item>
          <el-descriptions-item label="扬程">50m</el-descriptions-item>
          <el-descriptions-item label="功率">22kN</el-descriptions-item>
          <el-descriptions-item label="转速">2900r/min</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 运行状态 -->
      <div v-if="activeTab === 'status'" class="detail-content">
        <h3>当前状态</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运行状态">
            <el-tag type="success">{{ currentEquipment.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="运行时长">8760小时</el-descriptions-item>
          <el-descriptions-item label="维护周期">{{
            currentEquipment.maintenanceCycle
          }}</el-descriptions-item>
          <el-descriptions-item label="维护时间">2023-05-15</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">性能指标</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运行效率">95%</el-descriptions-item>
          <el-descriptions-item label="能耗指标">210 kWh</el-descriptions-item>
          <el-descriptions-item label="故障次数">2次</el-descriptions-item>
          <el-descriptions-item label="MTBF">4380小时</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 维护记录 -->
      <div v-if="activeTab === 'maintenance'" class="detail-content">
        <el-table :data="maintenanceRecords" border style="width: 100%">
          <el-table-column prop="date" label="维护日期" width="120" />
          <el-table-column prop="type" label="维护类型" width="120" />
          <el-table-column prop="content" label="维护内容" />
          <el-table-column prop="person" label="维护人" width="120" />
          <el-table-column prop="result" label="维护结果" width="120" />
        </el-table>
      </div>

      <!-- 故障记录 -->
      <div v-if="activeTab === 'fault'" class="detail-content">
        <el-table :data="faultRecords" border style="width: 100%">
          <el-table-column prop="date" label="故障日期" width="120" />
          <el-table-column prop="description" label="故障描述" />
          <el-table-column prop="level" label="故障等级" width="120">
            <template #default="{ row }">
              <el-tag :type="row.level === '严重' ? 'danger' : 'warning'">
                {{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="solution" label="解决方案" />
          <el-table-column prop="repairTime" label="修复时间" width="120" />
        </el-table>
      </div>

      <!-- 设备档案 -->
      <div v-if="activeTab === 'files'" class="detail-content">
        <el-table :data="equipmentFiles" border style="width: 100%">
          <el-table-column prop="name" label="文件名称" />
          <el-table-column prop="size" label="文件大小" width="120" />
          <el-table-column label="操作" width="120">
            <template #default>
              <el-button type="text">下载</el-button>
              <el-button type="text">预览</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dateilVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑设备对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="设备编号" prop="id">
          <el-input v-model="formData.id" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择设备类型">
            <el-option v-for="item in equipmentTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="formData.model" />
        </el-form-item>
        <el-form-item label="运行状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择运行状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用年限" prop="years">
          <el-input-number v-model="formData.years" :min="0" :max="50" />
        </el-form-item>
        <el-form-item label="所属区域" prop="area">
          <el-select v-model="formData.area" placeholder="请选择所属区域">
            <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="location">
          <el-input v-model="formData.location" />
        </el-form-item>
        <el-form-item label="维护周期" prop="maintenanceCycle">
          <el-select v-model="formData.maintenanceCycle" placeholder="请选择维护周期">
            <el-option label="1个月" value="1个月" />
            <el-option label="3个月" value="3个月" />
            <el-option label="6个月" value="6个月" />
            <el-option label="12个月" value="12个月" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂商" prop="manufacturer">
          <el-input v-model="formData.manufacturer" />
        </el-form-item>
        <el-form-item label="出厂日期" prop="productionDate">
          <el-date-picker v-model="formData.productionDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="安装日期" prop="installationDate">
          <el-date-picker v-model="formData.installationDate" type="date" placeholder="选择日期"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formData.manager" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 设备列表相关
const activeTab = ref("basic");
const loading = ref(false);
const equipmentList = ref([
  {
    id: "DEV-2023-001",
    name: "离心水泵",
    type: "水泵",
    model: "XQ-100",
    status: "正常运行",
    years: 2,
    area: "净水车间",
    location: "A区1号位",
    maintenanceCycle: "3个月",
    manufacturer: "上海水泵厂",
    productionDate: "2021-06-10",
    installationDate: "2021-07-05",
    manager: "张伟",
    phone: "13800138001",
  },
  {
    id: "DEV-2023-002",
    name: "电动阀门",
    type: "阀门",
    model: "DF-200",
    status: "待维护",
    years: 3,
    area: "沉淀池",
    location: "B区2号位",
    maintenanceCycle: "6个月",
    manufacturer: "北京阀门厂",
    productionDate: "2020-05-15",
    installationDate: "2020-06-20",
    manager: "李娜",
    phone: "13900139002",
  },
  {
    id: "DEV-2023-003",
    name: "PH传感器",
    type: "传感器",
    model: "PH-100",
    status: "故障维修",
    years: 1,
    area: "过滤池",
    location: "C区3号位",
    maintenanceCycle: "12个月",
    manufacturer: "深圳传感器公司",
    productionDate: "2022-08-12",
    installationDate: "2022-09-01",
    manager: "王强",
    phone: "13700137003",
  },
  {
    id: "DEV-2023-004",
    name: "PLC控制器",
    type: "控制器",
    model: "PLC-300",
    status: "正常运行",
    years: 4,
    area: "消毒间",
    location: "D区4号位",
    maintenanceCycle: "12个月",
    manufacturer: "西门子",
    productionDate: "2019-03-25",
    installationDate: "2019-04-10",
    manager: "赵敏",
    phone: "13600136004",
  },
  {
    id: "DEV-2023-005",
    name: "三相异步电机",
    type: "电机",
    model: "Y2-200",
    status: "停用",
    years: 5,
    area: "泵房",
    location: "E区5号位",
    maintenanceCycle: "6个月",
    manufacturer: "ABB电机",
    productionDate: "2018-11-08",
    installationDate: "2018-12-15",
    manager: "刘伟",
    phone: "13500135005",
  },
  {
    id: "DEV-2023-006",
    name: "石英砂过滤器",
    type: "过滤器",
    model: "SG-500",
    status: "正常运行",
    years: 2,
    area: "过滤池",
    location: "F区6号位",
    maintenanceCycle: "3个月",
    manufacturer: "德国过滤器公司",
    productionDate: "2021-09-18",
    installationDate: "2021-10-05",
    manager: "陈刚",
    phone: "13400134006",
  },
]);

// 搜索表单
const searchForm = reactive({
  keyword: "",
  type: "",
  status: "",
  area: "",
  dateRange: [],
  model: "",
  location: "",
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 6,
});

// 选项数据
const equipmentTypes = [
  { value: "水泵", label: "水泵" },
  { value: "阀门", label: "阀门" },
  { value: "传感器", label: "传感器" },
  { value: "控制器", label: "控制器" },
  { value: "电机", label: "电机" },
  { value: "过滤器", label: "过滤器" },
];

const statusOptions = [
  { value: "正常运行", label: "正常运行" },
  { value: "待维护", label: "待维护" },
  { value: "故障维修", label: "故障维修" },
  { value: "停用", label: "停用" },
];

const areaOptions = [
  { value: "净水车间", label: "净水车间" },
  { value: "沉淀池", label: "沉淀池" },
  { value: "过滤池", label: "过滤池" },
  { value: "消毒间", label: "消毒间" },
  { value: "泵房", label: "泵房" },
];

// 当前查看的设备详情
const currentEquipment = ref({});

// 维护记录数据
const maintenanceRecords = ref([
  {
    date: "2023-05-15",
    type: "定期维护",
    content: "更换润滑油，检查轴承磨损情况",
    person: "张伟",
    result: "正常",
  },
  {
    date: "2023-02-10",
    type: "定期维护",
    content: "检查密封件，紧固螺栓",
    person: "张伟",
    result: "更换密封圈",
  },
  {
    date: "2022-11-05",
    type: "定期维护",
    content: "全面检查设备运行状态",
    person: "李娜",
    result: "正常",
  },
]);

// 故障记录数据
const faultRecords = ref([
  {
    date: "2023-03-18",
    description: "电机过热导致停机",
    level: "严重",
    solution: "更换冷却风扇，清理散热片",
    repairTime: "4小时",
  },
  {
    date: "2022-12-25",
    description: "密封件泄漏",
    level: "一般",
    solution: "更换密封件",
    repairTime: "2小时",
  },
]);

// 设备档案数据
const equipmentFiles = ref([
  {
    name: "设备说明书.pdf",
    size: "2.5MB",
  },
  {
    name: "合格证.jpg",
    size: "1.2MB",
  },
  {
    name: "维护手册.pdf",
    size: "3.8MB",
  },
  {
    name: "电气原理图.dwg",
    size: "4.2MB",
  },
]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增设备");
const isEdit = ref(false);

// 表单数据
const formData = reactive({
  id: "",
  name: "",
  type: "",
  model: "",
  status: "正常运行",
  years: 0,
  area: "",
  location: "",
  maintenanceCycle: "3个月",
  manufacturer: "",
  productionDate: "",
  installationDate: "",
  manager: "",
  phone: "",
});

// 表单验证规则
const formRules = {
  id: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  model: [{ required: true, message: "请输入设备型号", trigger: "blur" }],
  status: [{ required: true, message: "请选择运行状态", trigger: "change" }],
  years: [{ required: true, message: "请输入使用年限", trigger: "blur" }],
  area: [{ required: true, message: "请选择所属区域", trigger: "change" }],
  location: [{ required: true, message: "请输入安装位置", trigger: "blur" }],
  maintenanceCycle: [
    { required: true, message: "请选择维护周期", trigger: "change" },
  ],
};

const formRef = ref(null);

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case "正常运行":
      return "success";
    case "待维护":
      return "warning";
    case "故障维修":
      return "danger";
    case "停用":
      return "info";
    default:
      return "";
  }
};
const dateilVisible = ref(false);
// 显示设备详情
const showEquipmentDetail = (equipment) => {
  currentEquipment.value = equipment;
  dateilVisible.value = true;
  activeTab.value = "basic";
};

// 切换标签页
const handleTabChange = (tab) => {
  activeTab.value = tab;
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = "新增设备";
  isEdit.value = false;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = "编辑设备信息";
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm("确认删除该设备信息吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      equipmentList.value = equipmentList.value.filter((item) => item.id !== id);
      ElMessage.success("删除成功");
      pagination.total -= 1;
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const batchDelete = () => {
  ElMessageBox.confirm("确认删除选中的设备信息吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      equipmentList.value = equipmentList.value.filter(
        (item) => !selectedIds.value.includes(item.id)
      );
      ElMessage.success("删除成功");
      pagination.total -= selectedIds.value.length;
      selectedIds.value = [];
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 处理提交
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑逻辑
        const index = equipmentList.value.findIndex(
          (item) => item.id === formData.id
        );
        if (index !== -1) {
          equipmentList.value[index] = { ...formData };
        }
        ElMessage.success("修改成功");
      } else {
        // 新增逻辑
        // 检查是否已存在相同ID
        if (equipmentList.value.some((item) => item.id === formData.id)) {
          ElMessage.error("该设备编号已存在");
          return;
        }
        equipmentList.value.unshift({ ...formData });
        ElMessage.success("新增成功");
        pagination.total += 1;
      }
      dialogVisible.value = false;
    }
  });
};

// 对话框关闭时重置表单
const handleDialogClose = () => {
  formRef.value?.resetFields();
  Object.keys(formData).forEach((key) => {
    if (key === "status") {
      formData[key] = "正常运行";
    } else if (key === "maintenanceCycle") {
      formData[key] = "3个月";
    } else if (key === "years") {
      formData[key] = 0;
    } else {
      formData[key] = "";
    }
  });
};

// 处理搜索
const handleSearch = () => {
  loading.value = true;
  // 模拟搜索
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = [];
    } else {
      searchForm[key] = "";
    }
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  // 这里可以调用获取数据的方法
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  // 这里可以调用获取数据的方法
};

// 选中的设备ID
const selectedIds = ref([]);

// 初始化数据
onMounted(() => {
  // 这里可以调用获取数据的API
});
</script>

<style scoped></style>